/**
 * @Description: 数据权限管理
 * @Date 2017/12/23
 * @Authoer: weimei
 * @Modified By:
 */
define([
  './themes/lang/' + window.YUFP_SYS_CONFIG.language + '/pages/content/systemManager/dataAuthManage/dataAuthManage.js',
  './custom/widgets/js/yufpExtTree.js'
], function (require, exports) {
  exports.ready = function (hashCode, data, cite) {
    var param = {};
    yufp.custom.vue({
      el: '#dataAuthManage',
      data: function () {
        var me = this;
        return {
          formdata: {},
          tmplFormdata: {},
          viewType: 'DETAIL',
          viewTitle: yufp.lookup.find('CRUD_TYPE', false),
          height: yufp.custom.viewSize().height - 20,
          dialogVisible: false,
          formDisabled: false,
          isChildNode: false,
          contrId: '',
          addFlag: false,
          tmplDialogVisible: false,
          authTmplId: '',
          createCheck: !yufp.session.checkCtrl('add'), // 新增按钮控制
          modifyCheck: !yufp.session.checkCtrl('modify'), // 修改按钮控制
          deleteCheck: !yufp.session.checkCtrl('delete'), // 删除按钮控制
          treeUrl: backend.appOcaService + '/api/adminsmdataauth/treequery',
          dataAuthUrl: backend.appOcaService + '/api/adminsmdataauth/getdataauth',
          tmplUrl: backend.appOcaService + '/api/adminsmdataauth/authtmplquery',
          dataTableColumns: [
            { label: this.$t('dataAuthManage.sjqxmb'), prop: 'authTmplName', sortable: true, resizable: true },
            { label: this.$t('dataAuthManage.sjqxtj'), prop: 'sqlString', width: 500, sortable: true, resizable: true },
            { label: this.$t('dataAuthManage.zjbgyh'), prop: 'lastChgName', sortable: true, resizable: true },
            { label: this.$t('dataAuthManage.zjbgsj'), prop: 'lastChgDt', sortable: true, resizable: true }
          ],
          tmplTableColumns: [
            { label: this.$t('dataAuthManage.sjqxmb'), prop: 'authTmplName', width: 403, sortable: true, resizable: true }
          ],
          dataFields: [
            {
              columnCount: 1,
              fields: [
                {
                  field: 'authTmplName',
                  label: this.$t('dataAuthManage.sjqxmb'),
                  readonly: true,
                  rows: 3,
                  focus: function (event) {
                    me.tmplDialogVisible = true;
                    me.$nextTick(function () {
                      if (me.addFlag) {
                        param = {
                          condition: JSON.stringify({
                            contrId: me.contrId ? me.contrId : null
                          })
                        };
                      } else {
                        param = {
                          condition: JSON.stringify({
                            contrId: me.$refs.dataTable.selections[0].contrId ? me.$refs.dataTable.selections[0].contrId : null
                          })
                        };
                      }
                      me.$refs.tmplTable.remoteData(param);
                    });
                  },
                  rules: [{ required: true, message: this.$t('dataAuthManage.btx'), trigger: 'blur' }]
                }
              ]
            }],
          dataFormButtons: [
            {
              label: this.$t('dataAuthManage.bc'),
              type: 'primary',
              hidden: false,
              op: 'submit',
              click: function (model) {
                me.saveCreateFn();
              }
            },
            {
              label: this.$t('dataAuthManage.bc'),
              type: 'primary',
              hidden: false,
              op: 'submit',
              click: function (model) {
                me.saveEditFn();
              }
            },
            {
              label: this.$t('dataAuthManage.qx'),
              hidden: false,
              click: function (model) {
                me.dialogVisible = false;
              }
            }
          ]
        };
      },
      methods: {
        // 左侧树节点点击事件,点击控制点节点查询关联数据权限模板信息
        nodeClickFn: function (nodeData, node, self) {
          var _this = this;
          _this.isChildNode = false;
          if (nodeData && nodeData.nodeType == 'C') {
            _this.isChildNode = true;
          }
          _this.contrId = nodeData.id;
          var param = {
            condition: JSON.stringify({
              contrId: _this.contrId ? _this.contrId : null
            })
          };
          _this.$refs.dataTable.remoteData(param);
        },
        // 操作状态选择
        switchStatus: function (viewType, editable) {
          this.viewType = viewType;
          this.dialogVisible = true;
          this.formDisabled = !editable;
          this.dataFormButtons[2].hidden = !editable;
          if (viewType == 'ADD') {
            this.dataFormButtons[0].hidden = !editable;
            this.dataFormButtons[1].hidden = editable;
          } else if (viewType == 'EDIT') {
            this.dataFormButtons[0].hidden = editable;
            this.dataFormButtons[1].hidden = !editable;
          }
        },
        // 新增
        dataAddFn: function () {
          if (this.isChildNode == false) {
            this.$message({ message: this.$t('dataAuthManage.qxxzkzdjd'), type: 'warning' });
            return;
          }
          this.switchStatus('ADD', true);
          this.addFlag = true;
          this.$refs.dataTable.clearSelection();
          this.$nextTick(function () {
            this.$refs.dataForm.resetFields();
          });
        },
        createFn: function () {
          var _this = this;
          _this.$refs.dataForm.formModel.contrId = _this.contrId;
          _this.$refs.dataForm.formModel.lastChgUsr = yufp.session.userId;
          _this.$refs.dataForm.validate(function (valid) {
            if (valid) {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmdataauth/createdataauth',
                data: _this.$refs.dataForm.formModel,
                callback: function (code, message, response) {
                  if (code == '0' && response.code == 0) {
                    _this.dialogVisible = false;
                    _this.addFlag = false;
                    _this.$message({ message: _this.$t('dataAuthManage.sjbccg') });
                    var param = {
                      condition: JSON.stringify({
                        contrId: _this.contrId ? _this.contrId : null
                      })
                    };
                    _this.$refs.dataTable.remoteData(param);
                    _this.authTmplId = '';
                  }
                }
              });
            } else {
              _this.$message({ message: _this.$t('dataAuthManage.qjcsrxsfhf'), type: 'warning' });
              return false;
            }
          });
        },
        saveCreateFn: function () {
          var _this = this;
          delete _this.$refs.dataForm.formModel.dataAuthId;
          if (_this.authTmplId.indexOf(',') != -1) {
            var authTmplIds = _this.authTmplId.split(',');
            var authTmplNames = _this.$refs.dataForm.formModel.authTmplName.split(',');
            for (var j = 0; j < authTmplIds.length; j++) {
              _this.$refs.dataForm.formModel.authTmplId = authTmplIds[j];
              _this.$refs.dataForm.formModel.authTmplName = authTmplNames[j];
              _this.createFn();
            }
          } else {
            _this.$refs.dataForm.formModel.authTmplId = _this.authTmplId;
            _this.createFn();
          }
        },
        // 修改
        modifyFn: function () {
          if (this.$refs.dataTable.selections.length < 1) {
            this.$message({ message: this.$t('dataAuthManage.qxxzytjl'), type: 'warning' });
            return;
          }
          if (this.$refs.dataTable.selections.length > 1) {
            this.$message({ message: this.$t('dataAuthManage.qxzytjl'), type: 'warning' });
            return;
          }
          this.switchStatus('EDIT', true);
          this.$nextTick(function () {
            yufp.extend(this.$refs.dataForm.formModel, this.$refs.dataTable.selections[0]);
          });
        },
        saveEditFn: function () {
          var _this = this;
          if (_this.authTmplId == '' || _this.authTmplId == undefined) {
            _this.authTmplId = _this.$refs.dataTable.selections[0].authTmplId;
          } else {
            if (_this.authTmplId.indexOf(',') != -1) {
              _this.$message({ message: _this.$t('dataAuthManage.xgsznxzygsjqxmb'), type: 'warning' });
              return;
            }
          }
          _this.$refs.dataForm.validate(function (valid) {
            _this.$refs.dataForm.formModel.authTmplId = _this.authTmplId;
            _this.$refs.dataForm.formModel.lastChgUsr = yufp.session.userId;
            if (valid) {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmdataauth/edtidataauth',
                data: _this.$refs.dataForm.formModel,
                callback: function (code, message, response) {
                  if (code == '0' && response.code == 0) {
                    _this.dialogVisible = false;
                    _this.$message({ message: _this.$t('dataAuthManage.sjbccg') });
                    var param = {
                      condition: JSON.stringify({
                        contrId: _this.contrId ? _this.contrId : null
                      })
                    };
                    _this.$refs.dataTable.remoteData(param);
                    _this.authTmplId = '';
                  }
                }
              });
            } else {
              _this.$message({ message: _this.$t('dataAuthManage.qjcsrxsfhf'), type: 'warning' });
              return false;
            }
          });
        },
        // 删除
        dataDeleteFn: function () {
          if (this.$refs.dataTable.selections.length < 1) {
            this.$message({ message: this.$t('dataAuthManage.qxxzytjl'), type: 'warning' });
            return;
          }
          var _this = this;
          if (_this.$refs.dataTable.selections) {
            var ids = '';
            for (var i = 0; i < _this.$refs.dataTable.selections.length; i++) {
              ids = ids + ',' + _this.$refs.dataTable.selections[i].authId;
            }
            _this.$confirm(_this.$t('dataAuthManage.scsjjtsscqsqsjqdsc'), _this.$t('dataAuthManage.ts'), {
              confirmButtonText: _this.$t('dataAuthManage.qr'),
              cancelButtonText: _this.$t('dataAuthManage.qx'),
              type: 'warning'
            }).then(function () {
              yufp.service.request({
                method: 'POST',
                data: {
                  id: ids
                },
                url: backend.appOcaService + '/api/adminsmdataauth/deletedataauth/' + ids,
                callback: function (code, message, response) {
                  if (code == '0' && response.code == 0) {
                    _this.$message({ message: _this.$t('dataAuthManage.sjsccg') });
                    var param = {
                      condition: JSON.stringify({
                        contrId: _this.contrId ? _this.contrId : null
                      })
                    };
                    _this.$refs.dataTable.remoteData(param);
                  }
                }
              });
            });
          }
        },
        // 选择可用数据权限模板
        getTmpl: function () {
          if (this.$refs.tmplTable.selections.length > 0) {
            var tmpl = this.$refs.tmplTable.selections;
            var authTmplName = '';
            var authTmplId = '';
            for (var n = 0; n < tmpl.length; n++) {
              authTmplName = authTmplName + ',' + tmpl[n].authTmplName;
              authTmplId = authTmplId + ',' + tmpl[n].authTmplId;
            }
            this.$refs.dataForm.formModel.authTmplName = authTmplName.substr(1);
            this.authTmplId = authTmplId.substr(1);
          }
          this.tmplDialogVisible = false;
        },
        // 左侧树节点类型图标
        renderContent: function () {
          var createElement = arguments[0];
          var type = arguments[1].data.nodeType;
          return createElement('span', [
            createElement('span', { attrs: { class: 'yu-treeMenuType' + type } }, type),
            createElement('span', arguments[1].node.label)
          ]
          );
        },
        load: function (node, resolve) {
          var me = this;
          var params = { nodeId: '0' };
          if (node.data.nodeId) {
            params.nodeId = node.data.nodeId;
            if (node.data.nodeType == 'F') {
              return resolve(node.data.children);
            } else if (node.data.nodeType == 'C') {
              return resolve([]);
            }
          }
          yufp.service.request({
            url: me.treeUrl,
            method: 'get',
            data: params,
            callback: function (code, message, response) {
              var data = response.data;
              var nodeArray = [];
              if (data && data.length > 0) {
                if (data[0].nodeType == 'M') { // 加载模块
                  nodeArray = data.map(function (item) {
                    return yufp.extend(true, item, {
                      id: item.nodeId,
                      label: item.nodeName,
                      pid: item.upTreeId
                    });
                  });
                } else { // 加载功能点和控制点
                  var funcMap = {};
                  for (var i = 0; i < data.length;) {
                    if (data[i].nodeType == 'F') { // 处理功能点数据
                      var func = data.splice(i, 1)[0];
                      funcMap[func.nodeId] = func;
                      funcMap[func.nodeId].id = func.nodeId;
                      funcMap[func.nodeId].label = func.nodeName;
                      funcMap[func.nodeId].pid = func.upTreeId;
                      funcMap[func.nodeId].children = [];
                    } else { // 处理控制点数据
                      data[i].id = data[i].nodeId;
                      data[i].label = data[i].nodeName;
                      data[i].pid = data[i].upTreeId;
                      data[i].isLeaf = true;
                      i++;
                    };
                  }
                  for (var j = 0; j < data.length; j++) { // 分配控制点
                    funcMap[data[j].upTreeId].children.push(data[j]);
                  }
                  for (var funcId in funcMap) { // 对象转数组
                    nodeArray.push(funcMap[funcId]);
                  }
                }
              }
              return resolve(nodeArray);
            }
          });
        }
      }
    });
  };
});
